import os

from django.conf import settings
from django.http import JsonResponse

from rest_framework.decorators import api_view
from rest_framework.response import Response

from XApiTestServer.models import ProjectInfo
from XApiTestServer.utils.auth import *
from XApiTestServer.utils.common import *
from XApiTestServer.utils.response import *
from XApiTestServer.utils.loader import *

import logging


logger = logging.getLogger('XApiTestServer')


IMPORT_TYPE_LIST = ['config', 'case']

@api_view(('POST',))
def load_json(request):
    # 获取上传的文件
    type = request.POST.get('type')
    belong_project = request.POST.get('belong_project')

    uploaded_file = request.FILES['file']

    if type not in IMPORT_TYPE_LIST:
        msg = "导入类型不正确"
        return Response(response_format(IMPORT_JSON_FAILED, msg))

    if not belong_project:
        msg = "未选择所属项目"
        return Response(response_format(IMPORT_JSON_FAILED, msg))
    belong_project = int(belong_project)

    if uploaded_file.size == 0:
        msg = "请上传有内容的文件！"
        return Response(response_format(IMPORT_JSON_FAILED, msg))

    _, file_extension = os.path.splitext(uploaded_file.name)
    if file_extension != '.json':
        msg = '错误：{}类型的文件暂不支持,请上传.json文件'.format(file_extension)
        return Response(response_format(IMPORT_JSON_FAILED, msg))

    json_content = uploaded_file.read()

    token = request.META.get("HTTP_X_TOKEN", None)
    author = get_username(token)

    if type == 'config':
        config_name, config_body = json_to_config_body(json_content)
        kwargs = {
            'name': config_name,
            'belong_project': belong_project,
            'config_body': config_body,
            'author': author
        }
        logging.info(kwargs)
        try:
            add_config_data(**kwargs)
        except Exception as e:
            msg = str(e)
            logging.error('导入配置失败: {msg}'.format(msg=msg))
            return Response(response_format(IMPORT_JSON_FAILED, msg))
    elif type == 'case':
        json_to_case(json_content)

    return Response(IMPORT_JSON_SUCCESS)
